package com.lagou.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 扫描指定包，递归获得包下所有的类
 */
public class SearchClassUtils {
    private static final String CLASS_SUFFIX = ".class";
    private static final String CLASS_FILE_PREFIX = File.separator + "classes" + File.separator;
    private static final String PACKAGE_SEPARATOR = ".";

    private SearchClassUtils() {
    }

    private static SearchClassUtils searClassUtils = new SearchClassUtils();

    public static SearchClassUtils getInstance() {
        return searClassUtils;
    }

    List<String> classPaths = new ArrayList<>();

    /**
     * @param basePack 包名
     */
    public List<String> getClasses(String... basePack) {

        for (String s : basePack) {
            //得到项目的classpath
            String classpath = SearchClassUtils.class.getResource("/").getPath();
            //将包名转换为路径名
            s = s.replace(".", File.separator);
            //合并 basePack 和 classpath
            String searchPath = classpath + s;

            doSearch(new File(searchPath));
        }

        return classPaths;

    }

    public void doSearch(File file) {
        if (file.isDirectory()) {//文件夹
            //文件夹我们就递归
            File[] files = file.listFiles();
            if (files == null) {
                return;
            }
            for (File f1 : files) {
                doSearch(f1);
            }
        } else {//标准文件
            //标准文件我们就判断是否是class文件
            if (file.getName().endsWith(".class")) {
                //如果是class文件我们就截取成全限定类名放入集合中。
                String path = file.getPath();
                path = path.replace(CLASS_SUFFIX, "");
                path = path.substring(path.indexOf(CLASS_FILE_PREFIX) + CLASS_FILE_PREFIX.length())
                        .replace(File.separator, PACKAGE_SEPARATOR);
                classPaths.add(path);
            }
        }

    }

    //查询接口的实现类
    public static List<Class<?>> getAllClassByInterface(Class<?> c) {
        List<Class<?>> returnClassList = new ArrayList<>();
        //判断是不是接口,不是接口不作处理
        if (c.isInterface()) {
            String packageName = c.getPackage().getName();    //获得当前包名
            try {
                List<Class<?>> allClass = getClasses(packageName);//获得当前包以及子包下的所有类

                //判断是否是一个接口
                for (Class<?> aClass : allClass) {
                    if (c.isAssignableFrom(aClass)) {
                        if (!c.equals(aClass)) {
                            returnClassList.add(aClass);
                        }
                    }
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return returnClassList;
    }

    /**
     * 根据包名获得该包以及子包下的所有类不查找jar包中的
     *
     * @param packageName 包名
     * @return List<Class < ?>>    包下所有类
     */
    private static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace(".", "/");
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            String newPath = resource.getFile().replace("%20", " ");
            dirs.add(new File(newPath));
        }
        List<Class<?>> classes = new ArrayList<>();
        for (File directory : dirs) {
            classes.addAll(findClass(directory, packageName));
        }
        return classes;
    }

    private static List<Class<?>> findClass(File directory, String packageName)
            throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        if (files == null) {
            return classes;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClass(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + "." + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }

}
